package com.cy;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.DefaultBlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 基于此类处理限流、熔断事件触发时出现的异常
 * 说明：
 * 1)系统有默认处理限流、熔断事件触发的异常的处理器吗？(DefaultBlockExceptionHandler)
 * 2)当默认处理异常的方式不满足业务需求时，我们需要自己定义异常处理器
 * 3)我们自己定义异常处理器时需要实现BlockExceptionHandler接口，
 *   并将异常处理器对象交给spring管理
 * 4)我们自己定义了异常处理器以后，默认的就无效了吗？(是的)，为什么呢？
 */
@Component
public class ServiceBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       BlockException e) throws Exception {
        Map<String,Object> map=new HashMap<>();
        map.put("status", 429);
        //map.put("message", "service is blocked");
        map.put("message", "访问太频繁、稍等片刻访问");
        //将map对象转换为json格式字符串
        String jsonStr=
        //借助jackson中的api(ObjectMapper)中的writeValueAsString方法进行转换
        new ObjectMapper().writeValueAsString(map);
        //设置响应数据编码
        httpServletResponse.setCharacterEncoding("utf-8");
        //告诉客户端(浏览器)你向它输出的数据类型及内容编码
        httpServletResponse.setContentType("text/html;charset=utf-8");
        PrintWriter out=httpServletResponse.getWriter();
        out.println(jsonStr);
        out.flush();
    }
}
